// Image Loader
// (c) jimon game studio

#include "CImageLoader.h"
#include "ILogManager.h"
#include "CImageFormatLoader_PNG.h"
#include "CImage.h"

namespace je
{
	namespace video
	{
		IMPLEMENT_SINGLETON(ImageLoader,JE_ENGINE_FUNCTION_CALL)

		#define ADD_IMAGE_LOADER(__format)\
			CImageFormatLoader_##__format * Loader__##__format;\
			JENEW(Loader__##__format,CImageFormatLoader_##__format);\
			Loaders->push_back(Loader__##__format);

		//! Constructor
		CImageLoader::CImageLoader()
		{
			JENEW(Loaders,ImageLoadersList)

			#ifdef JE_SUPPORT_FILEFORMAT_PNG
			ADD_IMAGE_LOADER(PNG)
			#endif

			SetImageLoader(this);
		}

		//! Destructor
		CImageLoader::~CImageLoader()
		{
			for(ImageLoadersList::Iterator Iter = Loaders->begin();Iter != Loaders->end();Iter++)
				JEDELETE(*Iter)

			Loaders->clear();

			JEDELETE(Loaders)

			SetImageLoader(NULL);
		}

		//! Load Image
		IImage * CImageLoader::LoadImage(core::IBuffer * DataBuffer)
		{
			for(ImageLoadersList::Iterator Iter = Loaders->begin();Iter != Loaders->end();Iter++)
				if((*Iter)->CanWorkWithThis(DataBuffer))
					return (*Iter)->LoadBuffer(DataBuffer);

			JELOG_W("Image file format not supported")

			u32 * Tmp;
			JENEW_A(Tmp,u32,64*64)

			CImage * Image;
			JENEW(Image,CImage(Tmp,jeVector2di(64,64),video::IImage::ICF_R8G8B8A8))
			
			JEDELETE_A(Tmp)

			return Image;
		}

		//! Save Image
		void CImageLoader::SaveImage(core::IBuffer * Buffer,IImage * Image,ImageFormat Format)
		{
			for(ImageLoadersList::Iterator Iter = Loaders->begin();Iter != Loaders->end();Iter++)
				if((*Iter)->GetImageFormat() == Format)
				{
					(*Iter)->SaveBuffer(Buffer,Image);
					return;
				}
		}

		//! Register Format Loader
		void CImageLoader::RegisterFormatLoader(IImageFormatLoader * FormatLoader)
		{
			Loaders->push_back(FormatLoader);
			FormatLoader->Grab();
		}

		//! UnRegister Format Loader
		void CImageLoader::UnRegisterFormatLoader(IImageFormatLoader * FormatLoader)
		{
			for(ImageLoadersList::Iterator Iter = Loaders->begin();Iter != Loaders->end();Iter++)
				if((*Iter) == FormatLoader)
				{
					FormatLoader->Drop();
					Loaders->erase(Iter);
				}
		}

		//! Get Format Loader
		IImageFormatLoader * CImageLoader::GetFormatLoader(ImageFormat Format)
		{
			for(ImageLoadersList::Iterator Iter = Loaders->begin();Iter != Loaders->end();Iter++)
				if((*Iter)->GetImageFormat() == Format)
					return *Iter;
			return NULL;
		}

	}
}
